<?php

namespace App\Services;

use App\Notifications\SmsCode;
use App\Notifications\SmsContent;
use App\Http\Response\Helper;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Notification;
use Illuminate\Validation\Validator;
use Leonis\Notifications\EasySms\Channels\EasySmsChannel;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
use Overtrue\EasySms\PhoneNumber;

class Sms
{
    use Helper;

    /**
     * @param PhoneNumber $phoneNumber
     */
    public function sendCode(PhoneNumber $phoneNumber)
    {
        try {
            Notification::route(EasySmsChannel::class, $phoneNumber)
                ->notify(new SmsCode());
        } catch (NoGatewayAvailableException $exception) {
            $raw = $exception->getException('winic')->raw;
            $this->error(70000, '短信发送失败:' . $raw[0]);
        }
    }

    /**
     * @param PhoneNumber $phoneNumber
     * @param $content
     */
    public function sendContent(PhoneNumber $phoneNumber, $content)
    {
        try {
            Notification::route(EasySmsChannel::class, $phoneNumber)
                ->notify(new SmsContent($content));
        } catch (NoGatewayAvailableException $exception) {
            $raw = $exception->getException('winic')->raw;
            \Log::error('短信发送失败:' . $raw[0]);
        }
    }

    /**
     * @param string    $attribute
     * @param mixed     $value
     * @param array     $parameters
     * @param Validator $validator
     *
     * @return bool
     */
    public function checkCode($attribute, $value, $parameters, $validator)
    {

        return Cache::pull('sms_code:' . $parameters[0]) == $value;
    }

    /**
     * @param string      $ip
     * @param PhoneNumber $phoneNumber
     */
    public function checkThrottle($ip, PhoneNumber $phoneNumber): void
    {
        if (Cache::get('throttle:sms_code:' . $phoneNumber->getUniversalNumber())) {
            $this->error(70001);
        }

        if (Cache::get('throttle:sms_code:' . $ip)) {
            $this->error(70001);
        }
    }

    /**
     * @param string      $ip
     * @param PhoneNumber $phoneNumber
     */
    public function setThrottle($ip, PhoneNumber $phoneNumber): void
    {
        // 每个手机号30秒内只能发送一条短信验证码
        Cache::add('throttle:sms_code:' . $phoneNumber->getUniversalNumber(), 1, now()->addSeconds(30));
        // 每个 IP 30秒内只能发送一条短信验证码
        Cache::add('throttle:sms_code:' . $ip, 1, now()->addSeconds(30));
    }
}
